package com.liugui;

/**
 * @ClassName: SynDemo
 * @Author: liugui
 * @Date: 2021-05-20 17:36
 **/
public class SynDemo {
    public static void main(String[] args) {
        MyThread7 m7 = new MyThread7();
        Thread t1 = new Thread(m7);
        Thread t2 = new Thread(m7);
        Thread t3 = new Thread(m7);

        t1.start();
        t2.start();
        t3.start();
    }
}

class MyThread7 implements Runnable {

    private int ticket = 5;

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            synchronized (this){ //同步当前对象
                if(ticket > 0){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("卖票：ticket = " + ticket --);
                    System.out.println("买票线程：" + Thread.currentThread().getName());
                }
            }
        }
    }
}